package org.kiwi.job.web.controller;

import org.apache.commons.lang3.StringUtils;
import org.kiwi.job.constant.CommonConstant;
import org.kiwi.job.service.ScheduleJobService;
import org.kiwi.job.vo.BaseResponse;
import org.kiwi.job.vo.JobVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

/**
 * @email jack.liu.19910921@gmail.com
 * Created by jack on 17/2/21.
 */
@RestController
@RequestMapping("/job")
public class JobController extends BaseController {

    @Autowired
    private ScheduleJobService scheduleJobService;

    @RequestMapping(value = "/scheduleJob", method = {RequestMethod.GET, RequestMethod.POST})
    public void scheduleJob(JobVO job, HttpServletResponse response) {
        BaseResponse resp = new BaseResponse();
        try {
            scheduleJobService.saveOrUpdateJob(job);
        } catch (Exception e) {
            resp.setStatus(CommonConstant.FAIL);
            resp.setError("500");
            resp.setMsg(StringUtils.defaultIfEmpty(e.getMessage(), e.getClass().getName()));
        }
        writerToJson(resp, response);
    }

    @RequestMapping(value = "/jobList", method = {RequestMethod.GET, RequestMethod.POST})
    public void jobList(HttpServletResponse response) {
        BaseResponse resp = new BaseResponse();
        resp.setData(scheduleJobService.queryAllJob());
        writerToJson(resp, response);
    }

    @RequestMapping(value = "/runningRecord/{jobCode}/{pageSize}/{pageNum}", method = {RequestMethod.GET, RequestMethod.POST})
    public void runningRecord(@PathVariable("jobCode") String jobCode,
                              @PathVariable("pageSize") Long pageSize,
                              @PathVariable("pageNum") Long pageNum,
                              HttpServletResponse response) {
        BaseResponse resp = new BaseResponse();
        resp.setData(scheduleJobService.queryRunningRecordForPage(jobCode, pageSize, pageNum));
        writerToJson(resp, response);
    }

}
